Integração Numérica

In [4]:
import matplotlib.pyplot as plt
import numpy as np
from ipywidgets import StaticInteract, RangeWidget

%matplotlib inline
plt.rcParams.update({'figure.max_open_warning': 0})
In [6]:
def f(x):
    return -12*x*x-2*x+4


a=-2 #limite inferior de integracao
b=2 #limite superior de integracao
#h=0.2 #numero de intervalos


def integracao(Retangulos):
    #fig = plt.figure()
    #ax1 = fig.add_subplot(111)
    h = (b-a)/float(Retangulos)
    fig, ax1 = plt.subplots()
    ax1.plot([a, b], [0, 0],c='g')
    soma=0
    for x in np.arange(a,b,h):
        soma=soma+h*(f(x)+f(x+h))/2

        ax1.plot([x, x], [0, f(x)],c='b')
        ax1.plot([x, x+h], [f(x), f(x+h)],c='b')

    ax1.plot([b, b], [0, f(b)],c='b')
    ## Integral da funcao
    real = (b**3*(-4.0)-b**2+b*4.0)-(a**3*(-4.0)-a**2+a*4.0)
    erro = np.abs(real - soma)
    
    output = "Real: {0}\nSoma: {1}\nErro:{2}\nh: {3}".format(real, soma, erro, h)
    ax1.text(-4, -160,
            output,
            fontsize=14, color='black')
    
    t = np.arange(a-1,b+1, 0.01)
    s = f(t)
    ax1.plot(t, s,c='r')
    return fig
    
StaticInteract(integracao,
               Retangulos=RangeWidget(1, 25, 1, default=5))
Out[6]:
Retangulos: 5